package com.cqw.order.service;

import com.alibaba.fastjson.JSON;
import com.cqw.constant.RedisKeyConstant;
import com.cqw.order.domain.Item;
import com.cqw.exception.CommonException;
import com.cqw.order.enums.ItemStateEnum;
import com.cqw.order.mapper.ItemMapper;
import com.cqw.vo.order.ItemReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-07-08 23:46
 * @Description: 商品分类service
 */
@Service
@Slf4j
public class ItemService {


    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 商品分类树
     */
    public List<Item> tree() {
        Long shopId = 1L;
        String key = RedisKeyConstant.ITEM_TREE_KEY + shopId;
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            //查询当前店铺的有效的分类
            Item item = new Item();
            item.setShopId(1L);
            item.setState(ItemStateEnum.ON_LINE);
            List<Item> itemList = itemMapper.selectBySelective(item);
            if (CollectionUtils.isEmpty(itemList)) {
                return null;
            }
            List<Item> items = toTree(itemList);
            redisTemplate.opsForValue().set(key, items, 30, TimeUnit.MINUTES);
            return items;
        }
        return (List<Item>) obj;
    }

    private List<Item> toTree(List<Item> itemList) {
        //拿到顶级分类
        List<Item> items = new ArrayList<>();
        itemList.forEach(item -> {
            if (item.getParentId() == 0) {
                items.add(item);
            }
        });

        //排序
        List<Item> itemSortList = items.stream().sorted(Comparator.comparing(Item::getSeq)).collect(Collectors.toList());

        //获取子节点
        itemSortList.forEach(item -> {
            List<Item> childList = getChild(item.getId(), itemList);
            item.setChild(childList);
        });
        return itemSortList;
    }


    private List<Item> getChild(Long parentId, List<Item> itemList) {
        List<Item> childList = new ArrayList<>();
        for (Item item : itemList) {
            if (item.getParentId().equals(parentId)) {
                childList.add(item);
            }
        }

        //递归
        for (Item item : childList) {
            List<Item> child = getChild(item.getId(), itemList);
            item.setChild(child);
        }

        //子节点排序
        return childList.stream().sorted(Comparator.comparing(Item::getSeq)).collect(Collectors.toList());
    }


    /**
     * 新增商品分类
     *
     * @param itemReq
     * @return
     */
    @Transactional(transactionManager = "oneTransactionManager", rollbackFor = Exception.class)
    public Item createItem(ItemReq itemReq) {
        log.info("ItemService createItem : {}", JSON.toJSONString(itemReq));
        //父节点id没有，默认是根节点
        if (itemReq.getParentId() == null) itemReq.setParentId(0L);

        Item item = new Item();
        item.setItemName(itemReq.getItemName());
        item.setShopId(itemReq.getShopId());
        List<Item> items = itemMapper.selectBySelective(item);
        if (CollectionUtils.isNotEmpty(items)) {
            List<String> itemNames = items.stream().map(Item::getItemName).collect(Collectors.toList());
            if (itemNames.contains(itemReq.getItemName())) {
                throw new CommonException("分类名称已存在，请确认！");
            }
        }

        Item insertParam = new Item(itemReq);
        //查询父节点相同的子节点
        item.setItemName(null);
        item.setShopId(itemReq.getShopId());
        item.setParentId(itemReq.getParentId());
        List<Item> subItems = itemMapper.selectBySelective(item);
        insertParam.setSeq(subItems.size() + 1);

        if (itemReq.getParentId() == 0) {
            insertParam.setGrade(1);
        } else {
            Item parentItem = itemMapper.selectByPrimaryKey(itemReq.getParentId());
            insertParam.setGrade(parentItem == null ? 1 : parentItem.getGrade() + 1);
        }

        itemMapper.insertSelective(insertParam);
        //删除缓存
        deleteCache(insertParam.getShopId());
        return insertParam;
    }


    /**
     * 修改商品类别
     *
     * @param itemReq
     * @return
     */
    @Transactional(transactionManager = "oneTransactionManager", rollbackFor = Exception.class)
    public Item updateItem(ItemReq itemReq) {
        log.info("ItemService updateItem:{}", JSON.toJSONString(itemReq));
        //修改只能修改名称，图片，图标
        Item updateParam = new Item();
        updateParam.setId(itemReq.getId());
        updateParam.setItemName(itemReq.getItemName());
        updateParam.setItemPic(itemReq.getItemPic());
        updateParam.setItemIcon(itemReq.getItemIcon());
        updateParam.setUpdateTime(new Date());
        itemMapper.updateByPrimaryKeySelective(updateParam);
        deleteCache(1L);
        return updateParam;
    }


    /**
     * 逻辑删除商品分类
     *
     * @param itemId
     * @return
     */
    public boolean deleteItem(Long itemId) {
        Item item = new Item();
        item.setId(itemId);
        item.setState(ItemStateEnum.OFF_LINE);
        int row = itemMapper.updateByPrimaryKeySelective(item);
        deleteCache(1L);
        return row > 0;
    }

    /**
     * 删除缓存
     *
     * @param shopId
     */
    public void deleteCache(Long shopId) {
        String key = RedisKeyConstant.ITEM_TREE_KEY + shopId;
        redisTemplate.delete(key);
    }


}
